package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.gulimall.search.config.ElasticSearchConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 满超
 * @date 2020/06/02
 **/
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Qualifier("restHighLevelClient")
    @Autowired
    RestHighLevelClient client;

    @Override
    public Boolean productStatusUp(List<SkuEsModel> esModels) throws IOException {

        //批量操作,可用于通过单个请求执行多个索引，更新和/或删除操作
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel esModel : esModels) {
            //把对象转化为json
            String json = JSON.toJSONString(esModel);

            //创建索引
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX)
                    .id(esModel.getSkuId().toString())
                    .source(json, XContentType.JSON);

            bulkRequest.add(indexRequest);
        }

        //进行处理
        BulkResponse bulkResponse = client.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);

        //如果至少一个操作失败，则此方法返回true
        boolean failures = bulkResponse.hasFailures();

        List<String> collect = Arrays.stream(bulkResponse.getItems()).map(BulkItemResponse::getId).collect(Collectors.toList());
        log.info("product商品上架完成，批量保存成功{},返回数据{}",collect,failures);

        return failures;
    }
}
